#include "reg.h"
#include "ui_reg.h"
#include "login.h"
#include <QCryptographicHash>
#include "../MainProject/sqlitedatabase.h"
#include "../MainProject/loggermanager.h"
Reg::Reg(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Reg)
{
    ui->setupUi(this);

}

Reg::~Reg()
{
    delete ui;
}

void Reg::on_gologinButton_clicked()
{
    Login* log = Login::getInstance();
    log ->show();
    this->hide();  // 隐藏当前窗口
}

void Reg::on_registerButton_clicked()
{   QString password;
    QString userName= ui->usernameLineEdit->text();
    QString  passwords= ui->passwordLineEdit->text();
    password=hashPassword(passwords);
    QString email =ui->emailLineEdit->text();
    QString phone=  ui->phoneLineEdit->text();
    bool phoneflag=true;
    bool emailflag=true;
    bool phonege=true;
    bool emailge=true;
    bool userNameflag=true;
    if(userName.isEmpty()){
        QMessageBox::information(this, "waring", "用户名不能为空");
     //   Logger().logError("输入的用户名为空");
    }
    else{

        //查询用户名
        SQLiteDatabase* db = SQLiteDatabase::getInstance();
        QString condition = QString("username = '%1'").arg(userName); // 设置条件字符串
        QJsonArray result = db->read("users", condition); // 调用read方法获取结果
        // for (const QJsonValue& value : result) {
        //     QJsonObject obj = value.toObject();
        //     qDebug() << "User:" << obj;
        // }
        if(!result.isEmpty()){

            QMessageBox::information(this, "waring", "用户名已存在");
            // Logger().logError("找不到要修改的用户");
            userNameflag=false;
        }
    }

    if(passwords.isEmpty()){
        QMessageBox::information(this, "waring", "密码不能为空");
      //  Logger().logError("输入的密码为空");
    }
    if(email.isEmpty()){
        QMessageBox::information(this, "waring", "邮箱不能为空");
     //   Logger().logError("输入的邮箱为空");
    }
    if(phone.isEmpty()){
        QMessageBox::information(this, "waring", "手机号不能为空");
       //  Logger().logError("输入的手机号为空");

    }
    if(!phone.isEmpty()){

        if(!validatePhoneNumber(phone)){
              QMessageBox::information(this, "waring", "手机号码格式不正确");
            return;
          //    Logger().logError("手机号码格式不正确");
        }else{
        //查询用户名
        SQLiteDatabase* db = SQLiteDatabase::getInstance();
        QString condition = QString("phone = '%1'").arg(phone); // 设置条件字符串
        QJsonArray result = db->read("users", condition); // 调用read方法获取结果
        // for (const QJsonValue& value : result) {
        //     QJsonObject obj = value.toObject();
        //     qDebug() << "User:" << obj;
        // }
        if(!result.isEmpty()){

            QMessageBox::information(this, "waring","该手机号已存在");

         //   Logger().logError("输入的手机号不正确");
            phoneflag=false;
        }
        }
    }

    if(!email.isEmpty()){
        if(!validateEmail(email)){
            QMessageBox::information(this, "waring", "邮箱格式不正确");
          //  Logger().logError("输入的邮箱格式不正确");
            emailge=false;
        }
        else{

        //查询邮箱
        SQLiteDatabase* db = SQLiteDatabase::getInstance();
        QString condition = QString("email = '%1'").arg(email); // 设置条件字符串
        QJsonArray result = db->read("users", condition); // 调用read方法获取结果
        // for (const QJsonValue& value : result) {
        //     QJsonObject obj = value.toObject();
        //     qDebug() << "User:" << obj;
        // }
        if(!result.isEmpty()){
            QMessageBox::information(this, "waring","该邮箱已存在");
          //  Logger().logError("输入的邮箱已存在");
            emailflag=false;
        }
        }
    }

    if(!userName.isEmpty()&&!passwords.isEmpty()&&!email.isEmpty()&&!phone.isEmpty() &&phoneflag && emailflag&&phonege &&emailge &&userNameflag){
        SQLiteDatabase* db = SQLiteDatabase::getInstance();

        // 创建记录

        QJsonObject user;
        user["username"] = userName;
        user["password"] = password;
        user["email"] = email;
        user["phone"] = phone;
        user["role"] = "user";
        db->create("users", user);
        //添加成功,
        QMessageBox::information(this, "success", "注册成功,请登录");
         // Logger().logInfo("注册成功");


    }
}

bool Reg::validateEmail(const QString &email)
{
    QRegularExpression regex(R"((^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$))");
    return regex.match(email).hasMatch();

}

bool Reg::validatePhoneNumber(const QString &phoneNumber)
{
    QRegularExpression regex(R"(^1[3-9]\d{9}$)");
    return regex.match(phoneNumber).hasMatch();
}

QString Reg::hashPassword(const QString &password)
{
    // 创建一个 QCryptographicHash 对象，设置其使用 MD5 算法
    QCryptographicHash hasher(QCryptographicHash::Md5);

    // 添加密码数据到哈希对象中（注意：转为 QByteArray）
    hasher.addData(password.toUtf8());

    // 计算哈希值并获取结果，转换为十六进制格式字符串
    QString hashedPassword = hasher.result().toHex();

    return hashedPassword;
}

